import React, { useState } from 'react';
import { Card, Input, Button, message, Spin, Result, Form } from 'antd';
import { ScissorOutlined } from '@ant-design/icons';
import { pdfApi } from '../../services/api';
import { handleApiError, downloadFile } from '../../utils/error';
import FileUploader from '../../components/common/FileUploader';

const PDFSplitter: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [form] = Form.useForm();

  const handleUpload = async (files: File[]) => {
    setFile(files[0]);
  };

  const handleSplit = async (values: { pageRanges: string }) => {
    if (!file) {
      message.warning('请先上传PDF文件');
      return;
    }

    setError(null);
    try {
      setLoading(true);
      const response = await pdfApi.splitPDF(file, values.pageRanges);
      downloadFile(response, 'split.pdf');
      message.success('拆分成功！');
      setFile(null);
      form.resetFields();
    } catch (err) {
      handleApiError(err);
      setError('拆分失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setFile(null);
    setError(null);
    form.resetFields();
  };

  return (
    <Card title="PDF拆分">
      {error ? (
        <Result
          status="error"
          title={error}
          extra={
            <Button type="primary" onClick={handleReset}>
              重试
            </Button>
          }
        />
      ) : (
        <>
          <FileUploader
            accept=".pdf"
            onUpload={handleUpload}
            loading={loading}
            description="请上传需要拆分的PDF文件"
          />

          {file && (
            <Form
              form={form}
              onFinish={handleSplit}
              style={{ marginTop: 16 }}
              initialValues={{ pageRanges: '1-' }}
            >
              <Form.Item
                label="页码范围"
                name="pageRanges"
                rules={[
                  { required: true, message: '请输入页码范围' },
                  {
                    pattern: /^(\d+(-\d+)?)(,\d+(-\d+)?)*$/,
                    message: '格式错误，示例：1-3,5,7-9'
                  }
                ]}
                extra="支持的格式：单页(如:1,3,5)，范围(如:1-3)，混合(如:1-3,5,7-9)"
              >
                <Input placeholder="请输入页码范围，如：1-3,5,7-9" />
              </Form.Item>

              <Form.Item>
                <Button.Group>
                  <Button
                    type="primary"
                    icon={<ScissorOutlined />}
                    htmlType="submit"
                    loading={loading}
                  >
                    拆分文件
                  </Button>
                  <Button onClick={handleReset} disabled={loading}>
                    重置
                  </Button>
                </Button.Group>
              </Form.Item>
            </Form>
          )}

          {loading && (
            <div style={{ textAlign: 'center', margin: '24px 0' }}>
              <Spin tip="正在拆分中..." />
            </div>
          )}
        </>
      )}
    </Card>
  );
};

export default PDFSplitter; 